import {Directive} from "@vue/runtime-core";

interface MyHtmlElement extends HTMLElement {
  __zhixin__setTimeer: number;
  __zhixin__mouseenter: Function;
  __zhixin__mouseleave: Function;
}

// 添加了数据类型记得下面判断也要添加
interface BindValue {
  time: number;
  call: Function;
  closeMouseEL: boolean;
}

const TimeChange:Directive<MyHtmlElement,BindValue> = {
  mounted(el,bind) {
    const createTime = ()=> {
      el.__zhixin__setTimeer = setInterval(()=>{
        bind.value.call(bind.value)
      },bind.value.time || 1000 * 10)
      if(!el.__zhixin__mouseenter){
        el.__zhixin__mouseenter=()=>{
          clearInterval(el.__zhixin__setTimeer)
        }
      }
      if(!el.__zhixin__mouseleave){
        el.__zhixin__mouseleave=()=>{
          createTime()
        }
      }
    }
    createTime()
    if(bind.value.closeMouseEL !== false){
      el.addEventListener('mouseenter',el.__zhixin__mouseenter)
      el.addEventListener('mouseleave',el.__zhixin__mouseleave)
    }
  },
  updated(el,bind){
    if(bind.value.time !== bind.oldValue.time
      || bind.value.call !== bind.oldValue.call
      || bind.value.closeMouseEL !== bind.oldValue.closeMouseEL
    ) {
      TimeChange.unmounted(el,bind)
      TimeChange.mounted(el,bind)
    }
  },
  unmounted(el) {
    clearInterval(el.__zhixin__setTimeer)
    el.removeEventListener('mouseenter',el.__zhixin__mouseenter)
    el.removeEventListener('mouseleave',el.__zhixin__mouseleave)
  }
}

export default TimeChange;
